#pragma once

#include <iostream>
#include <unordered_map>
#include <functional>
#include <ctime>

#include <sys/types.h>
#include <unistd.h>

using task_t = std::function<void()>;
static int number = 0;

void Download()
{
    std::cout << "我是下载任务..., pid:" << getpid() << std::endl;
}

void Log()
{
    std::cout << "我是日志任务..., pid:" << getpid() << std::endl;
}

void Sql()
{
    std::cout << "我是数据框同步任务..., pid:" << getpid() << std::endl;
}

class TaskManger
{
public:
    TaskManger()
    {
        srand(time(nullptr));
        InsertTask(Download);
        InsertTask(Log);
        InsertTask(Sql);
    };

    ~TaskManger(){};

    void InsertTask(task_t t)
    {
        tasks[number++] = t;
    }

    int SelectTask()
    {
        return rand() % number;
    }

    void ExcuteTask(int number)
    {
        if(tasks.find(number) == tasks.end()) return;
        tasks[number]();
    }

private:
    std::unordered_map<int, task_t> tasks;
};

TaskManger tm;

void Worker()
{
    while (true)
    {
        int task = 0;
        int n = ::read(0, &task, sizeof(task));
        if (n == sizeof(task))
        {
            tm.ExcuteTask(task);
        }
        else if (n == 0)
        {
            std::cout << "child pid: " << getpid() << " quiting..." << std::endl;
            break;
        }
        else
        {

        }
    }
}